﻿if select(2, UnitClass('player')) ~= "SHAMAN" then
	return
end
local L = AceLibrary("AceLocale-2.2"):new("Yata");
local BS = AceLibrary("Babble-Spell-2.2")
local deformat = AceLibrary("Deformat-2.0");
local YataTT = AceLibrary("Gratuity-2.0");
local Yata_TotemTiming = {L["(%d+) min"], L["(%d+) sec"]};
-- potential Blacklist to get around spells with the Totemstring and which aren't Totems at all
local Yata_SpellBlacklist = {BS["Totemic Call"]};



----------
-- Init --
----------

function Yata:TotemsInit()
	self.ElementsCount = {["Earth"] = 0, ["Fire"] = 0, ["Water"] = 0, ["Air"] = 0};
	self:GatherTotemData();
	if(#self.TotemData == 0) then 
		self:Print("No totems found, level too low?");
		self.db.profile.TotemsOrder = nil;
		return false;
	end
	for k,v in ipairs(Yata.TotemData) do
		local totem = Yata.TotemData[v];
		totem = totem[#totem];
		self.ElementsCount[totem.Element] = self.ElementsCount[totem.Element] + 1;
	end
	for i=1,3 do
		if(self.ElementsCount[self.db.profile.TotemsOrder[i]] == 0) then
			for j=i+1,4 do
				if(self.ElementsCount[self.db.profile.TotemsOrder[j]] ~= 0) then
					local backup = self.ElementsCount[self.db.profile.TotemsOrder[i]];
					self.ElementsCount[self.db.profile.TotemsOrder[i]] = self.ElementsCount[self.db.profile.TotemsOrder[j]];
					self.ElementsCount[self.db.profile.TotemsOrder[j]] = backup;
				end
			end
		end
	end
	self:CleanTotemProfile();
	return true;
end
---------------------------
-- Get Position by totem --
---------------------------

function Yata:GetPosByTotem(totem)
	local retval = 0;
	if(self.db.profile.TotemsOrder[totem.Element]) then
		for k,v in ipairs(self.db.profile.TotemsOrder[totem.Element]) do
			if(v == totem.Name) then retval = k;
				break;
			end
		end
	end
	return retval;
end

-----------------------------
-- Return count by element --
-----------------------------
function Yata:ReturnCountByElement(ele)
	return self.ElementsCount[ele];
end

-----------------------------
-- Return order by element --
-----------------------------

function Yata:ReturnOrderByElement(ele)
	local retval = 0;
	for i=1,4 do
		if(self.db.profile.TotemsOrder[i] == ele) then
			retval = i;
			break;
		end
	end
	return retval;
end

-----------------------
-- CleanTotemProfile --
-----------------------

function Yata:CleanTotemProfile()
	if(self.TotemData.Count ~= self.db.profile.TotemsCount) then
		for i=1,4 do
			if(self.db.profile.TotemsOrder[self.db.profile.TotemsOrder[i]]) then
				for k,v in ipairs(self.db.profile.TotemsOrder[self.db.profile.TotemsOrder[i]]) do
					if(not self.TotemData[v]) then 
						self:Print("Couldn't find: "..v..", removing it");
						table.remove(self.db.profile.TotemsOrder[self.db.profile.TotemsOrder[i]],k);
					end
				end
			end
		end
	end
end


-----------------------------
-- Utility functions below --
-----------------------------
function Yata:SpellBlacklist(spell)
	local blacklist = nil;
	for k,v in ipairs(Yata_SpellBlacklist) do
		if(spell == v) then
			blacklist = true;
			break;
		end
	end
	return blacklist
end

function Yata:GatherTotemData()
    self.TotemData = {};
    local tabs = GetNumSpellTabs();
    for tab = 2, tabs do
	local _, _, offset, numSpells = GetSpellTabInfo(tab);
	for i = 1, numSpells do
	    local spell = offset + i;
	    local SpellName, subspell = GetSpellName(spell, "spell");
	    if (string.find(string.lower(SpellName), string.lower(L["Totem"])) and not self:SpellBlacklist(SpellName)) then

		if (not self.TotemData[SpellName]) then
		    self.TotemData[SpellName] = {};
		    table.insert(self.TotemData, SpellName);
		end
		local totem = {};
		totem.SpellID = spell;
		totem.Name = SpellName;
		table.insert(self.TotemData[SpellName],totem);
	    end
	end
    end
    local count = 0;
    -- Add Spell Information (Cooldown,Duration, HP, Element)
    	
    	for k,v in ipairs(self.TotemData) do
    		for l,w in ipairs(self.TotemData[v]) do
			self:ExtractToolTip(w);
		end
		count = count + 1;
	end
    self.TotemData.Count = count;
end

--- Return Cooldown, Duration, HP, Element
--- Not yet fully converted to Gratuity/Deformat
function Yata:ExtractToolTip(totem)
	local element = "";
	totem.Element = "";
	totem.Cooldown = 0;
	totem.Health = 0;
	totem.Duration = 0;
	totem.Mana = 0;
	YataTT:SetSpell( totem.SpellID, "spell" );
	-- SpellTexture --
	totem.Texture = GetSpellTexture(totem.SpellID,"spell");	
	-- Mana cost --
	totem.Mana = YataTT:FindDeformat(MANA_COST,2,2,false,true);
	-- Element extraction --
	local _,_, element = YataTT:Find(L["Tools_totem_regex"],4,4,false,true);
	if( element ) then	
		-- localization hacks incoming --
		if GetLocale() ~= "zhTW" and GetLocale() ~= "koKR" and GetLocale() ~= "frFR" then
			if( string.sub( element, 1, 1 ) == "|" ) then
				element = string.sub( element, 11 );
			end
			_, _, element = string.find(element, "(%a*)");
			if( GetLocale() == "deDE" ) then
				if(element == "Erd") then
					element = "Erde"; -- "Werkzeuge: Erdtotem", rename Erd to Erde
				end
			end
		end
		totem.Element = L:GetReverseTranslation(element);
		if(not totem.Element) then
			self:Debug("Localization bug incoming");
		end
	end
	-- End Element --
	text = YataTT:GetLine(5,nil);
	-- Start HP --
	local _, _, health = YataTT:Find(L["(%d+) health"],5,5,false,true);
	if(not health) then
		_, _, health = YataTT:Find(L["(%d+) points health"],5,5,false,true);
	end
	if(not health) then
		health = 5;
	end
	totem.Health = health;
	-- End HP --
	-- Start Duration --     
	     local matches = {};
	     for num, regex in ipairs(Yata_TotemTiming) do
		     for k in string.gmatch(text, regex) do -- purple
	       		if(num == 1) then
	       			table.insert(matches,tonumber(k*60));
	       		else 	table.insert(matches,tonumber(k));
	       		end
		     end
	     end
	     table.sort(matches);
	     totem.Duration = matches[#matches];
	-- End Duration --
	-- Start Cooldown -- 
	local matches = {};
	text = YataTT:GetLine(3,true);
	if(text) then
	     for num, regex in ipairs(Yata_TotemTiming) do
		     for k in string.gmatch(text,regex) do
	       		if(num == 1) then
	       			table.insert(matches,tonumber(k*60));
	       		else 	table.insert(matches,tonumber(k));
	       		end
		     end
	     end
	     table.sort(matches);
	     totem.Cooldown = matches[#matches];
	end
	-- End Cooldown --
end
function Yata:OutputTotemData()
	for k,v in ipairs(self.TotemData) do
		for l,w in ipairs(self.TotemData[v]) do
			local output = string.format("%s Rank %i, HP: %s, Duration: %i, Element: %s, Cooldown: %i, Mana: %i", v,l,w.Health, w.Duration, w.Element, w.Cooldown, w.Mana);
			self:Print(output);
		end
	end
end
